package com.fjnu.dao.impl;

import com.fjnu.dao.UserDao;
import com.fjnu.entity.User;
import javax.sql.DataSource;
import java.sql.*;

public class UserDaoImpl implements UserDao {
    // 数据源：通过Spring注入
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void insert(User user) {
        String sql = "INSERT INTO user (user_id, username, password, salt, nickname, email, phone, sex, age, img, status, create_time, update_time, last_login_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        //  try-with-resources自动关闭资源（Connection/PreparedStatement）
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 设置参数（与User实体字段顺序对应）
            stmt.setString(1, user.getUserId());
            stmt.setString(2, user.getUsername());
            stmt.setString(3, user.getPassword());
            stmt.setString(4, user.getSalt());
            stmt.setString(5, user.getNickname());
            stmt.setString(6, user.getEmail());
            stmt.setString(7, user.getPhone());
            stmt.setInt(8, user.getSex());
            stmt.setInt(9, user.getAge());
            stmt.setString(10, user.getImg());
            stmt.setInt(11, user.getStatus());
            stmt.setTimestamp(12, new Timestamp(user.getCreateTime().getTime()));
            stmt.setTimestamp(13, new Timestamp(user.getUpdateTime().getTime()));
            stmt.setTimestamp(14, new Timestamp(user.getLastLoginTime().getTime()));

            stmt.executeUpdate(); // 执行插入
        } catch (SQLException e) {
            throw new RuntimeException("插入用户失败", e);
        }
    }

    @Override
    public User select(String userId) {
        String sql = "SELECT * FROM user WHERE user_id = ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            try (ResultSet rs = stmt.executeQuery()) { // 自动关闭ResultSet
                if (rs.next()) {
                    return mapRowToUser(rs); // 映射结果集到User对象
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询用户失败", e);
        }
        return null;
    }

    @Override
    public int count() {
        String sql = "SELECT COUNT(*) FROM user";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            if (rs.next()) {
                return rs.getInt(1); // 返回计数结果
            }
        } catch (SQLException e) {
            throw new RuntimeException("统计用户数量失败", e);
        }
        return 0;
    }

    // 工具方法：将ResultSet映射为User对象
    private User mapRowToUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setUserId(rs.getString("user_id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setSalt(rs.getString("salt"));
        user.setNickname(rs.getString("nickname"));
        user.setEmail(rs.getString("email"));
        user.setPhone(rs.getString("phone"));
        user.setSex(rs.getInt("sex"));
        user.setAge(rs.getInt("age"));
        user.setImg(rs.getString("img"));
        user.setStatus(rs.getInt("status"));
        user.setCreateTime(rs.getTimestamp("create_time"));
        user.setUpdateTime(rs.getTimestamp("update_time"));
        user.setLastLoginTime(rs.getTimestamp("last_login_time"));
        return user;
    }
}